package com.example.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ThreadPoolExecutor;

public class ForkJoinTest extends RecursiveTask<Integer> {
    private Integer start;
    private Integer end;
    private Integer edge=10000;
    private Integer sum=0;
    public ForkJoinTest(Integer start,Integer end){
        this.start=start;
        this.end=end;
    }

    @Override
    protected Integer compute() {
        if(end<edge){
            while (!end.equals(start)){
                sum=sum+start;
                start++;
                System.out.println(sum);
            }
            return sum;
        }else {
            ForkJoinTest forkJoinTest = new ForkJoinTest(start, end/2);
            forkJoinTest.fork();
            ForkJoinTest forkJoinTest1 = new ForkJoinTest(end / 2 + 1, end);
            forkJoinTest1.fork();
            return forkJoinTest.join()+forkJoinTest1.join();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTest forkJoinTest = new ForkJoinTest(0, 10000);
        forkJoinPool.execute(forkJoinTest);
        System.out.println(forkJoinTest.get());
//        ForkJoinTask<Integer> submit = forkJoinPool.submit(forkJoinTest);
//        Integer integer = submit.get();
//        System.out.println(integer);
//        forkJoinPool.shutdown();
    }
}
